#!/usr/bin/env python
# vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai

import sys
import re

def main():
    if len(sys.argv) < 3:
        print "Usage: %s" % sys.argv[0]
        sys.exit(2)

    nm_dict = {}
    nm_list = []
    nm_file = open(sys.argv[1], 'r')
    for nm_line in nm_file:
        nm_re = re.match('^(\w+) ([^dDWAU]) (\w+)', nm_line)
        if nm_re != None:
            #print "[%s]%s" % (nm_re.group(1), nm_re.group(3))
            nm_entry = [nm_re.group(1), nm_re.group(2), nm_re.group(3)]
            nm_dict[int(nm_re.group(1), 16)] = nm_re.group(3)
            nm_list.append(nm_entry)
            #if len(nm_dict) != len(nm_list):
            #    print "[%s]%s" % (nm_re.group(1), nm_re.group(3))
            #    break

    print "Number of Symbols %d" % len(nm_dict)
    print "Number of Symbols %d" % len(nm_list)
    #print nm_dict

    cl_last = 0
    cyg_stack = []
    cyg_file = open(sys.argv[2], 'r')
    for cyg_line in cyg_file:
        if re.match('^cygprofile*', cyg_line):
            print cyg_line
        cyg_re = re.match('(^[+-]) (\d+) (0x\w+) (0x\w+) (\d+)us', cyg_line)
        if cyg_re != None:
            cyg_addr = int(cyg_re.group(3), 16)
            if cyg_addr in nm_dict:
                cl_sym = nm_dict[cyg_addr]
            else:
                cl_sym = "0x%08x" % cyg_addr

            cl_type = cyg_re.group(1)
            cl_lev = int(cyg_re.group(2))
            cl_ret = cyg_re.group(4)
            cl_time = int(cyg_re.group(5))

            if cl_type == '+':
                print "%s%d%s %s(%s) -- %d ms dlt %d ms" % \
                    (("  " * cl_lev), cl_lev, cl_type, cl_sym, cl_ret, cl_time / 1000, (cl_time - cl_last) / 1000)
                cyg_stack.append(cl_time)
            else:
                cl_enter = cyg_stack.pop()
                print "%s%d%s %s(%s) -- %d ms dlt %d ms exe %d ms" % \
                    (("  " * cl_lev), cl_lev, cl_type, cl_sym, \
                    cl_ret, cl_time / 1000, (cl_time - cl_last) / 1000, (cl_time - cl_enter) / 1000)
            cl_last = cl_time

    
if __name__ == "__main__":
    main()
